package com.study.spmongodb.book.wwj.char19;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/30 10:09
 */
public class FutureServiceImpl<IN, OUT> implements FutureService<IN, OUT> {

    //为执行的线程指定名字前缀，
    private final static String FUTURE_THREAD_PREFIX = "FUTURE-";
    private final AtomicInteger nextCounter = new AtomicInteger();

    private String getNextName() {
        return FUTURE_THREAD_PREFIX + nextCounter.getAndIncrement();
    }

    @Override
    public Future<?> submit(Runnable runnable) {
        final FutureTask<Object> futureTask = new FutureTask<>();
        new Thread(() -> {
            runnable.run();
            //任务执行结束之后，将null作为结果传给 future
            futureTask.finish(null);
        }, "").start();
        return futureTask;
    }

    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input) {
        final FutureTask<OUT> futureTask = new FutureTask<>();
        new Thread(() -> {
            final OUT out = task.get(input);
            //任务执行结束之后，将null作为结果传给 future
            futureTask.finish(out);
        }, "").start();
        return futureTask;
    }
}
